package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    //获取配置文件指定变量的值
    @Value("${tencent.map.key}")
    private String key;
    //http远程调用工具
    @Autowired
    private RestTemplate restTemplate;

    //计算行驶路线
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //请求腾讯提供的接口，按照接口要求传递相关参数，返回需要的结果
        //使用httpClient调用接口，获取需要的数据
        //目前使用spring中提供的根据RestTemplate
        //定义需要调用的腾讯地址
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //封装需要传递的参数
        Map<String,String> map = new HashMap();
        //开始位置
        String start = calculateDrivingLineForm.getStartPointLatitude() + ","
                + calculateDrivingLineForm.getStartPointLongitude();
        map.put("from",start);
        //结束位置
        String end = calculateDrivingLineForm.getEndPointLatitude() + ","
                + calculateDrivingLineForm.getEndPointLongitude();
        map.put("to",end);
        //key
        map.put("key",key);
        //远程调用
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        //处理返回的结果
        //判断调用是否成功
        int status = result.getIntValue("status");
        if (status != 0) {
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        //获取返回路线相关信息
        JSONObject route = result.getJSONObject("result").getJSONArray("routes")
                .getJSONObject(0);
        //将返回的值封装到VO对象中
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //预估时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //距离  6.583 == 6.58 / 6.59
        drivingLineVo.setDistance(route.getBigDecimal("distance")
                .divide(new BigDecimal(1000))
                .setScale(2, RoundingMode.HALF_UP));//除以1000保留小数点后两位，然后向上取整
        //路线
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));

        return drivingLineVo;
    }
}
